
package edu.xhu.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.UpdateBean;

import edu.xhu.R;

/**
 * 
 * @author mjh
 * 该类用于升级操作
 *
 */
public class InstalApk {
	
	// 用到的四个常量
	private final int UPDATE_CLIENT = 0;
	private final int GET_UPDATE_ERROR = 1;
	private final int DOWN_ERROR = 2;
	private final int NO_UDATE_CLIENT = 3;
	
	private Context mContext;
	private UpdateBean info;
	private boolean bFirst;
	public InstalApk(Context context,UpdateBean bean, boolean bFirst) {
		this.mContext = context;
		info = bean;
		this.bFirst = bFirst;
	}
	
	/**
	 * 获取程序版本号
	 */
	private String getVersionName() throws Exception{
		PackageManager packageManager = mContext.getPackageManager();
		PackageInfo packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
	    return packInfo.versionName; 
	}
	
	/**
	 * 安装下载好的文件 
	 */
	private void installApk(File file) {  
	    Intent intent = new Intent();  
	    intent.setAction(Intent.ACTION_VIEW);  
	    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");  
	    mContext.startActivity(intent);  
	}  

	/**
	 * 检查是否有更新
	 */
	public void checkUpdate() {   
		
		Message msg = new Message();
		try {
			
			if(info.getVersion().equals(getVersionName())) {
				msg.what = NO_UDATE_CLIENT;
			} else {
				msg.what = UPDATE_CLIENT;
			}
			
			handler.sendMessage(msg);
		} catch (Exception e) {
			msg.what = GET_UPDATE_ERROR;
			handler.sendMessage(msg);
		}
	}
	
	/**
	 * 用于判断网络操作时的返回信息
	 */
	Handler handler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			
			switch(msg.what) {
			case UPDATE_CLIENT:
				showUpdataDialog();
				break;
			case DOWN_ERROR:
			case GET_UPDATE_ERROR:
				Toast.makeText(mContext, "下载失败", 0).show();
				break;
			case NO_UDATE_CLIENT:
				if(bFirst == false)
					Toast.makeText(mContext, "已是最新版本", 0).show();
				break;
			}
			
		};
	};

	/**
	 * 显示下载对话框
	 */
	protected void showUpdataDialog() {  
		LayoutInflater inflater = LayoutInflater.from(mContext);
		 
//	    AlertDialog dlg = new AlertDialog.Builder(mContext)
//	    .setTitle("提示")
//	    .setView(inflater.inflate(R.layout.update_dlg, null))
//	    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//			
//			public void onClick(DialogInterface arg0, int arg1) {
//				downloadUpdateApk();
//			}
//		})
//		.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//			
//			public void onClick(DialogInterface dialog, int which) {
//				CheckBox box = 
//			}
//		}).create();
//	    
//	    dlg.show();
		SharedPreferences sp = mContext.getSharedPreferences("update", mContext.MODE_WORLD_READABLE);
		boolean bSelected = sp.getBoolean("update", false);
		
		
		Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle("更新提醒");
		final View dlgView = inflater.inflate(R.layout.update_dlg, null);
		final CheckBox box = (CheckBox) dlgView.findViewById(R.id.checkbox_update);
		final TextView view = (TextView) dlgView.findViewById(R.id.textview_udpate);
		view.setText(info.getDescription());
		box.setChecked(bSelected);
		builder.setView(dlgView);
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
		{
			
			public void onClick(DialogInterface dialog, int which)
			{
				boolean bSelected  = box.isChecked();
				SharedPreferences sp = mContext.getSharedPreferences("update", mContext.MODE_WORLD_WRITEABLE);
				Editor editor = sp.edit();
				editor.putBoolean("update", bSelected);
				editor.putString("version", info.getVersion());
				Calendar calendar = Calendar.getInstance();
				editor.putLong("time", calendar.getTimeInMillis());
				editor.commit();
			}
		});
		
		builder.setNeutralButton("确定", new DialogInterface.OnClickListener()
		{
			
			public void onClick(DialogInterface dialog, int which)
			{
				
				downloadUpdateApk();
			}
		});
		builder.create();
		builder.show();
	} 
	
	/**
	 * 下载最新apk文件,先检查以前是否有过升级文件,如果有则删除掉原有文件
	 */
	private void downloadUpdateApk() {
		 final ProgressDialog pd;
		    pd = new  ProgressDialog(mContext);  
		    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
		    pd.setMessage("下载更新");  
		    pd.show();  
		  
	      new Thread()
	      {
				public void run() {
					try {  
		                File file = getFileFromServer(info.getUrl_apk()/*"http://10.0.2.2:8080/examples/123.apk"*/, pd);  
		                installApk(file);  
		                pd.dismiss(); //结束掉进度条对话框  
		                
		            } catch (Exception e) {  
		                pd.dismiss();
		            	Message msg = new Message();  
		                msg.what = DOWN_ERROR;  
		                e.printStackTrace();
		                handler.sendMessage(msg);  
		            }  
				};
				
				
	      }.start();
	} // downloadUpdateApk
	
	
	/**
	 * 从服务器下载更新的apk文件,并保存在本地
	 * @param path 保存的文件路径
	 * @param pd 下载进度条对话框
	 * @return 文件
	 * @throws Exception
	 */
	public File getFileFromServer(String path, ProgressDialog pd) throws Exception{
		
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			URL url = new URL(path);
			HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
		
			pd.setMax(conn.getContentLength());
			InputStream is = conn.getInputStream();
			

			String fileName = path.substring(path.lastIndexOf("/") + 1 );
			
			File file = new File("/mnt/sdcard/books/download/");
			if(!file.exists()) {
				file.mkdirs();
			}
			
			file = new File("/mnt/sdcard/books/download/" + fileName);
			
			if(file.exists())
				file.delete();
			file.createNewFile();
			
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024 * 1024];
			int len ;
			int total=0;
			while( ( len = bis.read(buffer)) != -1 ){
				fos.write(buffer, 0, len);
				total+= len;
				pd.setProgress(total);
			}
			
			fos.close();
			bis.close();
			is.close();
			
			return file;
		}
		
		return null;

	} // getFileFromServer
	
	
	
}
